<template>
  <el-dialog model-value="menuDialogVisible" title="分配权限" width="30%" @close="handleClose">


    <el-form ref="formRef" :model="form" label-width="100px">

      <el-tree style="max-width: 600px" :data="treeData" show-checkbox :props="defaultProps" ref="treeRef"
        :default-expand-all=false node-key="id" />

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>

import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil, { getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus'

const defaultProps = {
  children: 'children',
  label: 'name'
}


const props = defineProps(
  {
    id: {
      type: Number,
      default: -1,
      required: true
    },
    menuDialogVisible: {
      type: Boolean,
      default: false,
      required: true
    }
  }
)

const treeRef = ref({})
const treeData = ref([])
const form = ref({
  id: -1
})


const formRef = ref(null)

const initFormData = async (id) => {
  const res = await requestUtil.get("crmMenu/treeList");
  treeData.value = res.data.data;
  form.value.id = id;
  const res2 = await requestUtil.get("role/menus/" + id);

  const ids = res2.data.data;

  if (Array.isArray(ids) && ids.length > 0) {
    ids.forEach(id => {
      treeRef.value.setChecked(id, true, false)
    });
  }


}



watch(
  () => props.menuDialogVisible,
  () => {
    let id = props.id;
    if (id != -1 && props.menuDialogVisible) {
      initFormData(id)
    }
  }
)


const emits = defineEmits(['update:modelValue', 'initRoleList'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      var menuIds = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()];

      if (menuIds.length == 0) {
        ElMessage.warning("未选择数据")
      } else {
        let result = await requestUtil.post("role/updateMenus/" + form.value.id, menuIds);
        let data = result.data;
        if (data.code == 1) {
          ElMessage.success("执行成功！")

          emits("initRoleList")
          handleClose();
        } else {
          ElMessage.error(data.message);
        }
      }

    } else {
      ElMessage.warning("执行失败！")
    }
  })
}

</script>

<style scoped></style>
